package com.usian.controller;

import com.sun.xml.internal.stream.writers.WriterUtility;
import com.usian.pojo.Course;
import com.usian.pojo.Student;
import com.usian.service.StudentService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.channels.MulticastChannel;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("student")
public class StudentController {


    @Autowired
    private StudentService studentService;


    @RequestMapping("/page")
    public String page(){
        return "import";
    }



    @RequestMapping("import")
    public String exportList(@RequestParam("excelFile") MultipartFile file){
        List<Student> students = new ArrayList<>();
        List<Course> courses = new ArrayList<>();
        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            XSSFSheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row = sheet.getRow(i);
                String name = row.getCell(1).toString();
                int age = (int) row.getCell(2).getNumericCellValue();
                String sex = row.getCell(3).toString();
                Student student = new Student();
                student.setName(name);
                student.setAge(age);
                student.setSex("男".equals(sex)?1:2);
                students.add(student);
            }
            studentService.studentAll(students);
            XSSFSheet sheet1 = workbook.getSheetAt(1);
            int lastRowNum1 = sheet1.getLastRowNum();
            for (int i = 1; i <= lastRowNum1; i++) {
                XSSFRow row = sheet1.getRow(i);
                String sname = row.getCell(0).toString();
                Course course = new Course();
                course.setSname(sname);
                courses.add(course);
            }
            studentService.courseAll(courses);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "failure";
        }
    }

}
